package org.water.common.bind.method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
 * 解析返回数据
 * @author qzy
 *
 */
public  class ResultFormatReturnValueHandler implements HandlerMethodReturnValueHandler {

	
	/**
	 * 日期格式
	 */
	private String dateFormat="yyyy-MM-dd HH:mm:ss"; 
	/**
	 * 转换数据时，包名需要设置为空
	 */
	private String[] packageNameToEmptys={};
	
	/**
	 * 构造函数
	 */
	public ResultFormatReturnValueHandler() {
		ResultFormatReturnValue.instance().configXstream();
	}
	/**
	 * 构造函数
	 * @param dateFormat 日期格式
	 */
	public ResultFormatReturnValueHandler(String dateFormat) {
		if(dateFormat!=null)
		{
			this.dateFormat=dateFormat;
			ResultFormatReturnValue.dateFormat=this.dateFormat;
		}
		ResultFormatReturnValue.instance().configXstream();
	}
	/**
	 * 构造函数
	 * @param dateFormat 日期格式
	 */
	public ResultFormatReturnValueHandler(String dateFormat,String[] packageNames) {
		if(dateFormat!=null)
		{
			this.dateFormat=dateFormat;
			ResultFormatReturnValue.dateFormat=this.dateFormat;
		}
		if(packageNames!=null)
		{
			this.packageNameToEmptys=packageNames;
			ResultFormatReturnValue.instance().packageNameToEmptys=this.packageNameToEmptys;
		}
		ResultFormatReturnValue.instance().configXstream();
	}

	@Override
	public void handleReturnValue(Object obj, MethodParameter methodparameter,
			ModelAndViewContainer modelandviewcontainer, NativeWebRequest nativewebrequest) throws Exception {
		modelandviewcontainer.setRequestHandled(true);
		HttpServletRequest request=nativewebrequest.getNativeRequest(HttpServletRequest.class);
		HttpServletResponse response=nativewebrequest.getNativeResponse(HttpServletResponse.class);
		ResultFormatReturnValue.instance().setResultValue(obj,request,response);
	}
	
	/**
	 * 判断支持情况 
	 */
	@Override
	public boolean supportsReturnType(MethodParameter methodparameter) {
		//ResultFormat rf=methodparameter.getMethodAnnotation(ResultFormat.class);
		//if(rf!=null) return true;
		return true;
	}
	
}
